package admin

import (
	"go-weiqi-system/config"
	"go-weiqi-system/internal/models"
	"go-weiqi-system/internal/utils"
	"time"

	"github.com/gin-gonic/gin"
)

type AppointmentController struct{}

// Index 约棋报名列表
func (ctrl *AppointmentController) Index(c *gin.Context) {
	var param models.PageParam
	if err := c.ShouldBindQuery(&param); err != nil {
		param.Page = 1
		param.PageSize = 10
	}

	timeSlotID := c.Query("time_slot_id")
	status := c.Query("status")

	var appointments []models.Appointment
	var total int64

	db := config.DB.Model(&models.Appointment{}).
		Preload("User").
		Preload("AppointmentTime")

	if timeSlotID != "" {
		db = db.Where("time_slot_id = ?", timeSlotID)
	}
	if status != "" {
		db = db.Where("status = ?", status)
	}

	db.Count(&total)
	db.Order("id desc").
		Offset(param.GetOffset()).
		Limit(param.GetPageSize()).
		Find(&appointments)

	utils.Success(c, models.PageResponse{
		List:     appointments,
		Total:    total,
		Page:     param.GetPage(),
		PageSize: param.GetPageSize(),
	})
}

// UpdateStatus 更新状态
func (ctrl *AppointmentController) UpdateStatus(c *gin.Context) {
	var req struct {
		ID     uint   `json:"id" binding:"required"`
		Status string `json:"status" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		utils.Error(c, "参数错误")
		return
	}

	if err := config.DB.Model(&models.Appointment{}).
		Where("id = ?", req.ID).
		Update("status", req.Status).Error; err != nil {
		utils.Error(c, "更新失败")
		return
	}

	utils.Success(c, nil, "更新成功")
}

// BatchCheckIn 批量签到
func (ctrl *AppointmentController) BatchCheckIn(c *gin.Context) {
	var req struct {
		IDs []uint `json:"ids" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		utils.Error(c, "参数错误")
		return
	}

	checkInTime := time.Now().Format("2006-01-02 15:04:05")

	if err := config.DB.Model(&models.Appointment{}).
		Where("id IN ?", req.IDs).
		Updates(map[string]interface{}{
			"status":        "已完成",
			"check_in_time": checkInTime,
		}).Error; err != nil {
		utils.Error(c, "签到失败")
		return
	}

	utils.Success(c, nil, "签到成功")
}

// Statistics 统计
func (ctrl *AppointmentController) Statistics(c *gin.Context) {
	var totalCount int64
	var confirmedCount int64
	var completedCount int64

	config.DB.Model(&models.Appointment{}).Count(&totalCount)
	config.DB.Model(&models.Appointment{}).Where("status = ?", "已确认").Count(&confirmedCount)
	config.DB.Model(&models.Appointment{}).Where("status = ?", "已完成").Count(&completedCount)

	utils.Success(c, gin.H{
		"total_count":     totalCount,
		"confirmed_count": confirmedCount,
		"completed_count": completedCount,
	})
}

// Export 导出（简化版本，实际应返回CSV或Excel）
func (ctrl *AppointmentController) Export(c *gin.Context) {
	var appointments []models.Appointment
	config.DB.Preload("User").Preload("AppointmentTime").Find(&appointments)

	utils.Success(c, appointments, "导出成功")
}
